package mylab.io.base.model;

import com.fasterxml.jackson.annotation.JsonFormat;

import java.net.InetSocketAddress;
import java.time.LocalDateTime;

import mylab.base.foundation.lang.Identifiable;
import mylab.io.base.util.TerminalUtil;
import mylab.utils.common.CastUtil;
import mylab.utils.common.ReflectUtil;

public interface Msg extends Identifiable<String> {
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    LocalDateTime getTime();

    MsgType getType();

    void setType(MsgType type);

    Terminal getFrom();

    void setFrom(Terminal from);

    Terminal getTo();

    void setTo(Terminal to);

    String getCode();

    void setCode(String code);

    /**
     * 快速构造回复消息
     */
    default <T extends Msg> T reply(String responseMsgCode) {
        T response = reply();
        response.setCode(responseMsgCode);
        return response;
    }

    /**
     * 快速构造回复消息
     */
    default <T extends Msg> T reply() {
        T response = CastUtil.cast(ReflectUtil.newInstance(getClass()));
        response.setTo(getFrom());
        return response;
    }

    default void setTerminal(Endpoint from, Endpoint to) {
        setFrom(TerminalUtil.socketTerminal(from));
        setTo(TerminalUtil.socketTerminal(to));
    }

    default void setTerminal(InetSocketAddress from, InetSocketAddress to) {
        setFrom(TerminalUtil.socketTerminal(from));
        setTo(TerminalUtil.socketTerminal(to));
    }

    default void setTerminal(Terminal from, Terminal to) {
        setFrom(from);
        setTo(to);
    }

}
